package com.kede.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kede.dao.RoleDao;
import com.kede.dao.UserDao;
import com.kede.entity.Menu;
import com.kede.dao.MenuDao;
import com.kede.entity.Role;
import com.kede.entity.User;
import com.kede.service.MenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 【请填写作者】
 * @since 2020-03-27
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuDao, Menu> implements MenuService {

    @Autowired
    MenuDao menuDao;

    @Autowired
    RoleDao roleDao;

    @Autowired
    UserDao userDao;
    private User getByUserName(String name) {
        QueryWrapper<User> Wrapper = new QueryWrapper<User>();
        Wrapper.eq("username",name);
        User one=userDao.selectOne(Wrapper);
        return one;
    }

    @Override
    public List<Menu> getCurrentMenuListByRoleId() {
        //查询当前用户的所有菜单的树形结构
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        User user=getByUserName(username);

        //找到这个人的所有角色
        List<Role> roleList = roleDao.getListByUserId(user.getId());

        //找到这个人的所有菜单 可能有重复
       Set<Menu> roleSet=new LinkedHashSet<>();//Set集合去重复
        for (Role role: roleList) {
           List<Menu> menuList = menuDao.getListByRoleId(role.getId());
            roleSet.addAll(menuList);
        }
        //得到菜单的树形结构

        Map<Long,Menu> map=new HashMap<>();
        //jdk8 的lambda表达式 等同于下方遍历
        //roleSet.forEach(Menu -> map.put(Menu.getId(),Menu));

        for (Menu menu : roleSet) {
            map.put(menu.getId(),menu);
        }

        //rootMenu 顶级菜单
        List<Menu> rootMenu=new LinkedList<>();
        for (Menu menu : roleSet) {
            if (menu.getPid()==0){//加入顶级菜单
                rootMenu.add(menu);
            }
        }
        for (Menu menu : roleSet) {
            if (menu.getPid()==0){//加入顶级菜单
                continue;
            }
            //不是顶级菜单把自己加入父级菜单
            Menu parentMenu = map.get(menu.getPid());
            parentMenu.getChild().add(menu);

        }
        return rootMenu;
    }

    @Override
    public List<Menu> getListByRoleId(Long id) {
        return menuDao.getListByRoleId(id);
    }
}
